import os
from fastapi import APIRouter,status
from fastapi.responses import FileResponse
from fastapi.exceptions import HTTPException


from app.robot.const import PATH_ROBOT_INSTANCE
from app.robot.commons import get_robot_instances,zip_files,makeup_robot_instance_task_name

task_app = APIRouter()


@task_app.get("/task/{pid}/{task_id}")
def get_task(pid: str, task_id: str):
    """
    获取指定ID的任务文件
    :param pid: 机器人实例名, *表示所有实例下查找
    :param task_id: 任务ID
    :return:
    """
    files = []
    if pid != "*":
        if os.path.exists(os.path.join(PATH_ROBOT_INSTANCE, pid)):
            task_file = makeup_robot_instance_task_name(os.path.join(PATH_ROBOT_INSTANCE, pid), task_id)
            if os.path.exists(task_file):
                files.append(task_file)
        else:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="机器人实例不存在")
    else:
        paths = get_robot_instances()
        if not paths:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="机器人实例不存在")
        for path in paths:
            task_file = makeup_robot_instance_task_name(path, task_id)
            if os.path.exists(task_file):
                files.append(task_file)

    if len(files) == 0:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="指定ID的任务文件不存在")
    zip_file = zip_files(files)
    return FileResponse(path=zip_file, filename=os.path.basename(zip_file))